import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

// 修复路由重复跳转报错
const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}


const router = new Router({
    mode: 'hash',
    routes: [
        {
            path: '/register',
            name: 'Register',
            component: () => import('@/page/RegisterPage.vue')
        },
        {
            path: '/login',
            name: 'Login',
            component: () => import('@/page/LoginPage.vue')
        },
        {
            path: '/',
            name: 'Home',
            component: () => import('@/page/HomePage.vue')
        },
        {
            path: '/UsersPage',
            name: 'UsersPage',
            component: () => import('@/page/UserPage.vue')
        },
        {
            path: '*',
            redirect: '/'
        }
    ]
})

router.beforeEach((to, from, next) => {
    const publicPages = ['/login', '/register'] // 免验证页面
    const authRequired = !publicPages.includes(to.path)
    const token = localStorage.getItem('token') || sessionStorage.getItem('token')

    if (authRequired && !token) {
        next('/login?redirect=' + encodeURIComponent(to.fullPath))
    } else {
        next()
    }
})

export default router